#include "widget.h"
#include "ui_widget.h"


Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    tcpSocket = new QTcpSocket(this);

    this->setWindowTitle("TCP客户端");

    connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(receiveMessages()));

    connect(tcpSocket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),this,SLOT(mStateChanged(QAbstractSocket::SocketState)));
}

Widget::~Widget()
{
    delete ui;
}

void Widget::receiveMessages()
{

    ui->textBrowser->append("来自服务器的消息："+tcpSocket->readAll());
}

void Widget::mStateChanged(QAbstractSocket::SocketState state)
{
    switch (state){

    case QAbstractSocket::UnconnectedState:
        ui->textBrowser->append("与服务器断开连接！");
        ui->startTcpClient->setEnabled(true);
        ui->stopTcpClient->setEnabled(false);
        break;

    case QAbstractSocket::ConnectedState:
        ui->textBrowser->append("连接服务器成功！");
        ui->startTcpClient->setEnabled(false);
        ui->stopTcpClient->setEnabled(true);
        break;
    default:
        break;
    }
}




void Widget::on_sendMessage_clicked()
{
    //发送消息

    if(tcpSocket->state()==QAbstractSocket::ConnectedState)
    {
       tcpSocket->write(ui->lineEdit->text().toUtf8());
    }
    else{
        ui->textBrowser->append("请连接服务器！");
    }

}

void Widget::on_startTcpClient_clicked()
{
    bool ok = false;
    //连接服务器ip地址和端口
    tcpSocket->connectToHost(QHostAddress(ui->adresslineEdit->text()),ui->portlineEdit->text().toUShort(&ok));
}

void Widget::on_stopTcpClient_clicked()
{
    //断开服务器
    tcpSocket->disconnectFromHost();
}
